package com.joven.shelltest.utils;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.annotation.TableField;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * 反射获取类的类类型及字段属性
 * @Author: wzj
 * @Date: 2024/3/28 8:58
 */
public class ChangeBeanUtil {

    public static final String COMMA_SYMBOL = ",";
    public static final String EMPTY = "";

    public static Map<Object, Object> contrastObj(Object oldBean, Object newBean) {
        Map<Object, Object> resultList = new HashedMap<Object, Object>();
        try {
            // 通过反射获取类的类类型及字段属性
            Class<? extends Object> clazz = oldBean.getClass();
            Class<? extends Object> newClazz = newBean.getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                // 排除序列化属性
                if ("serialVersionUID".equals(field.getName())) {
                    continue;
                }
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(newClazz, field.getName());

                // 获取对应属性值
                Method getMethod = pd.getReadMethod();
                Object o1 = getMethod.invoke(oldBean);
                Object o2 = null;
                if (!ObjectUtils.isEmpty(sourcePd)) {
                    Method getNewMethod = sourcePd.getReadMethod();
                    // 如果类型是List类型
                    if ("interface java.util.List".equals(sourcePd.getPropertyType().toString())) {
                        o2 = getNewMethod.invoke(newBean);
                        List<String> arrayList = Convert.toList(String.class, o2);
                        o2 = convertToString(COMMA_SYMBOL, arrayList);
                    } else {
                        o2 = getNewMethod.invoke(newBean);
                    }
                }
                if (o2 == null || EMPTY.equals(o2)) {
                    continue;
                }

                if ((o1 == null) || !o2.toString().equals(o1.toString())) {
                    resultList.put(field.getAnnotation(TableField.class).value(), o2);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }

    public static String convertToString(String symbol, List<String> stringList) {

        if (CollectionUtils.isEmpty(stringList) || !StringUtils.hasText(symbol)) {
            return "";
        }
        return String.join(symbol, stringList);
    }
}
